/*
 * Copyright (c) 2023-2025 elsfs Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.elsfs.cloud.common.mybatis.injector.methods;

import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.toolkit.sql.SqlScriptUtils;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;
import org.elsfs.cloud.common.mybatis.ext.mybatis.extension.JoinWrapper;

/** 查询连表统计 */
public class SelectJoinCount extends AbstractJoinMethod {
  /** SQL脚本 */
  private static final String SQL_SCRIPT =
      "<script>%s SELECT COUNT(%s) FROM %s %s %s %s\n</script>";

  public SelectJoinCount() {
    super("selectJoinCount");
  }

  /**
   * 注入自定义 MappedStatement
   *
   * @param mapperClass mapper 接口
   * @param modelClass mapper 泛型
   * @param tableInfo 数据库表反射信息
   * @return MappedStatement
   */
  @Override
  public MappedStatement injectMappedStatement(
      Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {
    String sql =
        String.format(
            SQL_SCRIPT,
            this.sqlFirst(),
            "1",
            tableInfo.getTableName() + " AS " + JoinWrapper.TABLE_ALIAS,
            SqlScriptUtils.unSafeParam(JOIN_SQL_METHOD),
            this.sqlWhereEntityWrapper(true, tableInfo),
            this.sqlComment());

    SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
    return this.addSelectMappedStatementForOther(
        mapperClass, this.methodName, sqlSource, Long.class);
  }
}
